package com.fwzc.giuseppe.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Base64;

/**
 * 本地数据存储管理
 */
public class PreferencesManage {

	/** SharedPreferences名称 */
	private static final String SP_NAME = "giuseppe";

	/** 用户key */
	public static final String KEY_USER = "user";

	/**
	 * 读取对象
	 * 
	 * @param context
	 *            上下文（当前activity）
	 * @param key
	 *            要读取对象的名称
	 * @param defObject
	 *            如果读取不到返回什么对象
	 * @return
	 */
	public static Object readObject(Context context, String key,
			Object defObject) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				SP_NAME, Context.MODE_PRIVATE);
		String userValue = sharedPreferences.getString(key, "");
		if (userValue.equals(""))
			return defObject;
		byte[] userByte = Base64.decode(userValue.getBytes(), Base64.DEFAULT);
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				userByte);
		try {
			ObjectInputStream objectInputStream = new ObjectInputStream(
					byteArrayInputStream);
			return objectInputStream.readObject();
		} catch (Exception e) {
			return defObject;
		}
	}

	/**
	 * 保存对象
	 * 
	 * @param context
	 *            上下文（当前activity）
	 * @param key
	 *            要保存对象的名称
	 * @param object
	 *            要保存的对象
	 */
	public static void saveObject(Context context, String key, Object object) {
		SharedPreferences sharedPreferences = context.getSharedPreferences(
				SP_NAME, Context.MODE_PRIVATE);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ObjectOutputStream objectOutputStream;
		try {
			objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
			objectOutputStream.writeObject(object);
			String objValue = new String(Base64.encode(
					byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
			Editor editor = sharedPreferences.edit();
			editor.putString(key, objValue);
			editor.commit();
			objectOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
